﻿using MediatR;
using Medical.Api.Read.Application.Command.BasicManagement.DeviceDictionaryCommand;
using Medical.Api.Read.Application.Command.Wms.WmsStorageCommand;
using Medical.Domain.BasicManagement;
using Medical.Domain.Wms;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;
using Medical.Api.Read.Dto.WmsDto.WmsStorageDto;

namespace Medical.Api.Read.Application.Handler.Wms.WmsStorageHandler
{
    /// <summary>
    /// 入库分页查询处理器
    /// </summary>
    public class QueryStorageHandler : IRequestHandler<QueryStorageCommand, ApiResult<ApiPageIng<WmsStoragePageDto>>>
    {
        private readonly IBaseRepository<WmsStorage> _wmsStorageRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="equipmentRepository">设备仓储</param>
        public QueryStorageHandler(IBaseRepository<WmsStorage> wmsStorageRepository)
        {
            _wmsStorageRepository = wmsStorageRepository;
        }

        public Task<ApiResult<ApiPageIng<WmsStoragePageDto>>> Handle(QueryStorageCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<ApiPageIng<WmsStoragePageDto>>();
            try
            {
                // 获取未逻辑删除的入库数据
                var query = _wmsStorageRepository.GetAll().Where(x => !x.IsDeleted);
                var dto = request.QueryDto;

                // 按入库编号模糊查询
                if (!string.IsNullOrWhiteSpace(dto.StorageCode))
                {
                    query = query.Where(x => x.StorageCode.Contains(dto.StorageCode));
                }
                // 按入库状态过滤
                if (dto.AuditState.HasValue)
                {
                    query = query.Where(x => x.AuditState == dto.AuditState.Value);
                }
                // 按创建时间范围过滤（开始时间）
                if (dto.StartTime.HasValue)
                {
                    query = query.Where(x => x.CreateTime >= dto.StartTime.Value);
                }
                // 按创建时间范围过滤（结束时间）
                if (dto.EndTime.HasValue)
                {
                    query = query.Where(x => x.CreateTime <= dto.EndTime.Value);
                }

                // 统计总数
                int total = query.Count();
                // 分页查询，按创建时间倒序
                var pageData = query
                    .OrderByDescending(x => x.CreateTime)
                    .Skip((dto.PageIndex - 1) * dto.PageSize)
                    .Take(dto.PageSize)
                    .Select(x => new WmsStoragePageDto
                    {
                        Id = x.Id,
                        StorageCode = x.StorageCode,
                        StorageType = (int)x.StorageType,
                        StorageTypeName = x.StorageType.ToString(),
                        Warehouse = (int)x.Warehouse,
                        WarehouseName = x.Warehouse.ToString(),
                        Supplier = (int)x.Supplier,
                        SupplierName = x.Supplier.ToString(),
                        StorageExplain = x.StorageExplain,
                        AuditState = x.AuditState,
                        AuditName = x.AuditName,
                        AuditDate = x.AuditDate,
                        CreateTime = x.CreateTime
                    })
                    .ToList();

                result.Code = ApiEnums.Success;
                result.Msg = "查询成功";
                result.Data = new ApiPageIng<WmsStoragePageDto>
                {
                    PageData = pageData,
                    TotalCount = total
                };
            }
            catch (Exception ex)
            {
                result.Code = ApiEnums.Error;
                result.Msg = $"查询异常: {ex.Message}";
                result.Data = null;
            }
            return Task.FromResult(result);
        }
    }
}
